#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import sys
import mrget
import strict_hwcfg
sys.path.append('/usr/lib64/fpemud-os-sysman')
from fm_util import InfoPrinter
from helper_pkg_warehouse import PkgWarehouse
from helper_pkg_warehouse import PkgMerger


p = InfoPrinter(indent=int(sys.argv[1]))
curPythonVer = sys.argv[2]
oldNewestPythonVer = sys.argv[3]
curRubyVer = sys.argv[4]
oldNewestRubyVer = sys.argv[5]

mrget.init(system_or_user=True)

p.incIndent()
pkgwh = PkgWarehouse()
bBuild = False

while curPythonVer != "":
    assert oldNewestPythonVer != ""
    newVer = pkgwh.pythonGetValidNewestVersion(curPythonVer)
    if oldNewestPythonVer != curPythonVer:
        # user delibrately keep using an old version when a new version is valid
        assert pkgwh.pythonGetCurrentVersion() == curPythonVer  # FIXME: will python version be auto raised? should we revert to the old version?
        p.printInfo("- Python version is kept not changed.")
        break
    if newVer == curPythonVer:
        # no valid newer version
        assert pkgwh.pythonGetCurrentVersion() == curPythonVer  # FIXME: will python version be auto raised? should we revert to the old version?
        p.printInfo("- Python version is not changed.")
        break
    if True:
        # update python version
        p.printInfo("- Updating Python version to %s..." % (newVer))
        pkgwh.pythonUpdateToVersion(newVer)
        pkgwh.pythonRefreshTargetUseFlags()
        bBuild = True
        break

while curRubyVer != "":
    assert oldNewestPythonVer != ""
    newVer = pkgwh.rubyGetValidNewestVersion(curRubyVer)
    if oldNewestRubyVer != curRubyVer:
        # user delibrately keep using an old version when a new version is valid
        assert pkgwh.rubyGetCurrentVersion() == curRubyVer  # FIXME: will ruby version be auto raised? should we revert to the old version?
        p.printInfo("- Ruby version is kept not changed.")
        break
    if newVer == curRubyVer:
        # no valid newer version
        assert pkgwh.rubyGetCurrentVersion() == curRubyVer  # FIXME: will ruby version be auto raised? should we revert to the old version?
        p.printInfo("- Ruby version is not changed.")
        break
    if True:
        p.printInfo("- Updating Ruby version to %s..." % (newVer))
        pkgwh.rubyUpdateToVersion(newVer)
        pkgwh.rubyRefreshTargetUseFlags()
        bBuild = True
        break

if bBuild:
    p.printInfo("- Updating @world again...")
    maintPkgSets = pkgwh.getMaintPkgSets()
    PkgMerger(strict_hwcfg.probe()).doEmerge("-1 -uDN --with-bdeps=y @world @preserved-rebuild %s" % (" ".join(maintPkgSets)))

print("")
